package com.dwxt.cdms.service;


import com.alibaba.fastjson.JSON;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.dwxt.cdms.api.common.utils.DateUtil;
import com.dwxt.cdms.api.common.utils.StringUtil;
import com.dwxt.cdms.base.Page;
import com.dwxt.cdms.constant.TaskMessageData;
import com.dwxt.cdms.dao.CustomerMapper;
import com.dwxt.cdms.dao.HealthWarnRecordMapper;
import com.dwxt.cdms.dao.TaskMessageMapper;
import com.dwxt.cdms.entity.Customer;
import com.dwxt.cdms.entity.HealthMessage;
import com.dwxt.cdms.entity.TaskMessage;
import com.dwxt.cdms.entity.TaskMessageExample;
import com.dwxt.cdms.util.UUIDUtil;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.util.PartyUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

@Service
public class TaskMessageService {

    @Autowired
    private TaskMessageMapper taskMessageMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private HealthWarnRecordMapper healthWarnRecordMapper;

    @Autowired
    private SendSmsRequest sendSmsRequest;
    @Autowired
    private IAcsClient iAcsClient;


    public BaseResult page(Page page) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        TaskMessageExample example = new TaskMessageExample();
        example.setOrderByClause("create_time desc");
        List<TaskMessage> taskMessageList = taskMessageMapper.selectByExample(example);
        PageInfo pageInfo = new PageInfo(taskMessageList);
        return BaseResult.ok(pageInfo);
    }

    public List<TaskMessage> list() {
        TaskMessageExample example = new TaskMessageExample();
        List<TaskMessage> taskMessageList = taskMessageMapper.selectByExample(example);
        return taskMessageList;
    }

    public BaseResult add(TaskMessage taskMessage) {
        String currentUserId = PartyUtil.getCurrentUserId();
        if (taskMessage.getId() == null) {
            taskMessage.setCreateUser(Integer.valueOf(currentUserId));
            taskMessage.setId(UUIDUtil.getUUID());
            taskMessageMapper.insertSelective(taskMessage);
        } else {
            taskMessage.setUpdateUser(Integer.valueOf(currentUserId));
            taskMessageMapper.updateByPrimaryKeySelective(taskMessage);
        }
        if (!taskMessage.getType().equals(TaskMessageData.TYPE_BIRTHDAY)) {
            TaskMessageData.setRedisValue(taskMessage);
        }
        return BaseResult.ok();
    }

    public BaseResult delete(String id) {
        taskMessageMapper.deleteByPrimaryKey(id);
        return BaseResult.ok();
    }

    public TaskMessage selectById(String id) {
        return taskMessageMapper.selectByPrimaryKey(id);

    }

    public void updateStatusToFinish(TaskMessage taskMessage) {
        TaskMessage entity = new TaskMessage();
        entity.setId(taskMessage.getId());
        entity.setSendTime(new Date());
        entity.setStatus("1");
        entity.setCount(taskMessage.getCount()+1);
        taskMessageMapper.updateByPrimaryKeySelective(entity);
    }

    public void sendBirthdayMessage() {
        String today = DateUtil.parseStr(new Date(), DateUtil.FMT_MMDD);
        if (StringUtil.isBlank(today)) {
            return;
        }
        List<Customer> list = customerMapper.selectByBirthday(today);
        TaskMessageExample example = new TaskMessageExample();
        example.createCriteria().andTypeEqualTo(TaskMessageData.TYPE_BIRTHDAY);
        List<TaskMessage> taskMessages = taskMessageMapper.selectByExample(example);
        if (taskMessages != null && taskMessages.size() > 0) {
            TaskMessage taskMessage = taskMessages.get(0);
            for (Customer customer : list) {
                //小程序
                HealthMessage msg = new HealthMessage();
                msg.setType(taskMessage.getTitle());
                msg.setCustomerId(customer.getId());
                msg.setCrateTime(new Date());
                msg.setId(UUID.randomUUID().toString());
                String name = customer.getName() == null ? "" : customer.getName();
                String content = taskMessage.getContent().replace("username",name);
                msg.setContent(content);
                healthWarnRecordMapper.insertMessage(msg);
                // 短信
                sendSmsRequest.setPhoneNumbers(customer.getPhone());   //接收号码
                // 控制台创建的模板CODE
                sendSmsRequest.setTemplateCode("151547101 SMS_234031506");
                HashMap<Object, Object> map = new HashMap<>();
                map.put("name", name);//消息
                sendSmsRequest.setTemplateParam(JSON.toJSONString(map));// 短信模板中的变量；数字需要转换为字符串；个人用户每个变量长度必须小于15个字符。"
                try {
                    SendSmsResponse httpResponse = iAcsClient.getAcsResponse(sendSmsRequest);
                } catch (Exception e) {

                }
            }
        }

    }
}
